'use strict';
const fs = require('fs-extra');
const nodePath = require('path');
const signale = require('signale');
const config = require('./config');
const defaults = require('./defaults');
const log = require('./components/logger');
const deleteEmpty = require('delete-empty');
const multibar = require('./components/multibar');
const downloadState = require('./components/downloadState');
const trackListDownload = require('./components/trackListDownload');
const { multipleWhitespacesToSingle, sanitizeFilename, ensureDir } = require('./components/utils');
/**
 * Download multiple tracks with the given DownloadType
 *
 * @param {DownloadType} downloadType
 */
const downloadMultiple = async (downloadType, path, quality) => {
  let albumList = downloadType.album ? downloadType.album : {};
  log.debug(`Got track list info for ${downloadType.type}: ${downloadType.title} (${downloadType.id})`);
  downloadState.setDownloadTypeName(downloadType.title);

  if (!(0 < downloadType.tracks.length)) {
    signale.warn('No tracks to download for ' + downloadType.type + '/' + downloadType.title);
    return { error: 'NO TRACKS!' };
  }

  // We don't want to generate a playlist file if this is no playlist
  if (downloadType.type == 'playlist') {
    defaults.PLAYLIST_FILE_ITEMS = {};
  } else {
    defaults.PLAYLIST_FILE_ITEMS = null;
  }

  try {
    downloadState.updateNumberTracksToDownload(downloadType.tracks.length);
    const value = await trackListDownload(downloadType.tracks, albumList, path, quality, defaults.CONCURRENCY);
    multibar.stop();
    // Generate the playlist file
    if (defaults.PLAYLIST_FILE_ITEMS) {
      const playlistName = multipleWhitespacesToSingle(sanitizeFilename(downloadType.title));
      const playlistRoot = config.get('saveLayout.playlistRoot', path);
      const playlistFile = nodePath.join(playlistRoot, playlistName, playlistName + '.m3u8');

      let playlistFileContent = '';
      let playlistFileContentInPlace = '';
      let itemsToCopy = [];

      downloadType.tracks.forEach((trackInfos) => {
        if (defaults.PLAYLIST_FILE_ITEMS[trackInfos.SNG_ID]) {
          const playlistFileItem = defaults.PLAYLIST_FILE_ITEMS[trackInfos.SNG_ID];
          const filename = nodePath.basename(playlistFileItem.trackSavePath);

          playlistFileContent += './' + filename + '\r\n';
          playlistFileContentInPlace += playlistFileItem.trackSavePath + '\r\n';

          itemsToCopy.push({
            name: filename,
            path: playlistFileItem.trackSavePath,
            move: playlistFileItem.move,
          });
        }
      });

      if (itemsToCopy.length > 0) {
        if (playlistRoot == path) {
          fs.writeFileSync(
            nodePath.join(path, playlistName + '.m3u8'),
            playlistFileContentInPlace.replace(new RegExp(path, 'g'), '.')
          );
        } else {
          ensureDir(playlistFile);
          for (const item of itemsToCopy) {
            if (item.move) {
              await fs.move(item.path, nodePath.join(nodePath.dirname(playlistFile), item.name), { overwrite: true });
            } else {
              fs.copy(item.path, nodePath.join(nodePath.dirname(playlistFile), item.name), { overwrite: false });
            }
          }

          fs.writeFileSync(playlistFile, playlistFileContent);
          deleteEmpty(path);
        }
      } else {
        signale.warn('Failed to generate playlist. No tracks!');
      }
    }

    return value;
  } catch (err) {
    log.debug(err);
    throw err;
  }
};

module.exports = downloadMultiple;
